import defineds from './defineds.js'
let BASE_URL = defineds['BASE_URL']
let utilMd5 = require('./md5.js')
let request_flag = {}
let http = {
	post: (url, data) => {
		let that = this
		let phpsessid = uni.getStorageSync('PHPSESSID');
    let utoken = uni.getStorageSync("utoken");
		let openid = uni.getStorageSync("openid");
		let headers = {
			'Content-Type': 'application/x-www-form-urlencoded'
		}
		let time = new Date().getTime()
		let sort = utilMd5.hexMD5('admin')
		headers.time = time
		headers.sort = sort
		headers.sign = utilMd5.hexMD5(sort + time)
		if (openid) data['openid'] = openid;
		// 旧接口
		data['comp_id'] = defineds.compid; //识别公司
		if (phpsessid) {
			data['phpsessid'] = phpsessid;
			headers['Cookie'] = 'PHPSESSID=' + phpsessid;
		} 
		if (utoken) data['utoken'] = utoken;
    
		return new Promise((resolve, reject) => {
			uni.request({
				url: BASE_URL + url,
				method: 'POST',
				header: headers,
				data: data,
				success: res => {
					// 删除fail标志
					if (request_flag.hasOwnProperty(url)) {
						delete request_flag[url];
					}
					if (typeof res.data == 'object') {
						resolve(res.data)
					} else {
						reject()
						uni.showModal({
							title: '调用失败,请联系管理员',
							showCancel: false
						})
					}
				},
				fail: (err) => {
					if (request_flag.hasOwnProperty(url)) {
						delete request_flag[url]
						uni.showModal({
							title: "服务信息超时，请稍候再试",
							showCancel: false,
							complete: function(res) {}
						})
						return
					}
					request_flag[url] = 1
					http.post(url, data)
					reject(err)
				},
				complete: () => {}
			})
		})
		
	}
}

export default http
